package org.ccay.manage.registry.cluster.impl;

import java.text.MessageFormat;

import javax.inject.Inject;
import javax.inject.Named;

import org.ccay.async.AsyncMessage;
import org.ccay.async.IMessageProcessor;
import org.ccay.async.IMessageSender;
import org.ccay.core.exception.ApplicationException;
import org.ccay.manage.registry.servlet.RegistrySyncServlet;
import org.ccay.registry.events.IRegistryChangedHandler;
import org.ccay.registry.events.RegistryChangedEventArgs;
import org.ccay.ws.service.IClusterInvokeService;

/**
 * 注册项改变事件
 * @author chaowangbang
 * @since 2017年6月12日
 *
 */
@Named
public class ClusterRegistryChangedHandler implements IRegistryChangedHandler, IMessageProcessor{
	@Inject
	private IMessageSender messageSender;
	
	/* (non-Javadoc)
	 * @see www.ccay.org.ccay.core.cache.ehcache.ICacheEventHandler#execute(java.lang.Object, www.ccay.org.ccay.core.cache.ehcache.CacheEvent)
	 */
	public void execute(Object sender, RegistryChangedEventArgs args) throws ApplicationException {
		if(sender.getClass().equals(RegistrySyncServlet.class)){
			//忽略来自servlet的同步更新，避免循环触发
			return;
		}
		AsyncMessage message = new AsyncMessage("RegistrySync");
		message.setContent(args);
		//使用异步框架处理此事件
		messageSender.send(message);
	}
	
	@Inject
	private IClusterInvokeService cluster; 
	/* (non-Javadoc)
	 * @see www.ccay.org.ccay.async.IMessageProcessor#process(www.ccay.org.ccay.async.AsyncMessage)
	 */
	public void process(AsyncMessage message) throws ApplicationException {
		RegistryChangedEventArgs e = (RegistryChangedEventArgs)message.getContent();
		String query = MessageFormat.format("name={0}",e.getRegistryItemName());		
		cluster.invoke("servlet/registry", query);
	}

}
